/*
 * Copyright (c) 2020 Carnegie Lee
 * All rights reserved
 */
package com.geekc.rediscache.service;

import com.geekc.rediscache.domain.Order;
import com.geekc.rediscache.util.BloomFilterHelper;
import com.geekc.rediscache.util.BloomFilterUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 订单业务类
 * @author Carnegie Lee
 */
@Service
public class OrderService {

    @Autowired
    private BloomFilterUtil bloomFilterUtil;

    @Autowired
    private BloomFilterHelper<String> bloomFilterHelper;

    @PostConstruct
    private void initBloomFilter() {
        List<Order> list = this.getOrderList();
        for (Order order : list) {
            bloomFilterUtil.addBloomFilter(bloomFilterHelper, "order_existed_bloom", String.valueOf(order.getOrderId()));
        }
    }

    @Cacheable(value = "order" /** 缓存器 */, key = "#orderId" /** Redis Key（SPEL表达式） */, condition = "#orderId != 1")
    public Order getOrderById(int orderId) {
        Order order = new Order(orderId, "owner0" + orderId, "goods0" + orderId,
                "示例商品0" + orderId, orderId, new Date(), 100.0 * orderId);
        if (!bloomFilterUtil.includeByBloomFilter(bloomFilterHelper, "order_existed_bloom", String.valueOf(orderId))) {
            return null;
        } else
            return order;
    }

    @Cacheable(value = "order:rank:amount")
    public List<Order> getOrderList() {
        List<Order> list = new ArrayList<>();
        for (int i = 1; i < 10; i++) {
            Order order = new Order(i, "owner0" + i, "goods0" + i,
                    "实例商品" + i, 1, new Date(), 100.0 * i);
            list.add(order);
        }
        return list;
    }

    @CachePut(value = "order", key = "#order.orderId")
    //@CachePut(value = "order", keyGenerator = "keyGenerator")
    public Order createOrder(Order order) {
        System.out.println("生成订单[编号：" + order.getOrderId() + "]");
        return order;
    }

    @CachePut(value = "order", key = "#order.orderId")
    public Order updateOrder(Order order) {
        System.out.println("更新订单[编号：" + order.getOrderId() + "]信息");
        return order;
    }

    @CacheEvict(value = "order", key = "#orderId")
    public void deleteOrderById(int orderId) {
        System.out.println("删除订单[编号：" + orderId + "]");
    }
}
